package com.thiswhyme.sentinel.server2.feign.fallback;

import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.google.common.reflect.TypeToken;
import com.thiswhyme.common.response.ResponseVo;
import com.thiswhyme.sentinel.server2.feign.UserFeign2Service;
import feign.RetryableException;

import java.lang.reflect.Type;

/**
 * 自定义fallback
 * Created by thiswhyme on 2020/9/3.
 */
public class UserFeign2FallbackService implements UserFeign2Service {

    private Throwable throwable;

    UserFeign2FallbackService(Throwable throwable) {
        this.throwable = throwable;
    }

    @Override
    public ResponseVo<String> queryUserName(Integer userId) {
        return defaultFallBack(new TypeToken<String>(){}.getType());
    }

    @Override
    public ResponseVo<String> queryUserName2(Integer userId) {
        return defaultFallBack(new TypeToken<String>(){}.getType());
    }

    @Override
    public ResponseVo<String> queryUserName3(Integer userId) {
        return defaultFallBack(new TypeToken<String>(){}.getType());
    }

    private <T> ResponseVo<T> defaultFallBack(Type type) {
        System.out.println(throwable);

        if(throwable instanceof BlockException) {
            if(throwable instanceof DegradeException) {
                return ResponseVo.failure("4271", "自定义-服务熔断") ;
            } else if(throwable instanceof FlowException) {
                return ResponseVo.failure("4272", "自定义-服务限流") ;
            } else if(throwable instanceof ParamFlowException) {
                return ResponseVo.failure("4273", "自定义-热点参数限流") ;
            }
            return ResponseVo.failure("427", "自定义-其他限流") ;
        } else if(throwable instanceof RetryableException) {
            if(null != throwable.getCause() && null != throwable.getCause().getCause() && throwable.getCause().getCause() instanceof BlockException) {
                if(throwable.getCause().getCause() instanceof DegradeException) {
                    return ResponseVo.failure("4271", "自定义-ip-服务熔断") ;
                } else if(throwable.getCause().getCause() instanceof FlowException) {
                    return ResponseVo.failure("4272", "自定义-ip-服务限流") ;
                } else if(throwable.getCause().getCause() instanceof ParamFlowException) {
                    return ResponseVo.failure("4273", "自定义-ip-热点参数限流") ;
                }
                return ResponseVo.failure("427", "自定义-ip-其他限流") ;
            }
        }

        return ResponseVo.failure("403", "自定义 feign fallback-" + throwable.getMessage());
    }
}
